import os
import json
import shutil
from pathlib import Path
import shell_executive as s_e
import precedent_values as pv


def delete_directory(path_str):
    if os.path.exists(path_str):
        shutil.rmtree(path_str)
        print(path_str, "目录已删除")
    else:
        print(path_str, "指定的路径不存在")


def get_command_lines(dir_path, voice_pattern, immedia_decide) -> list:
    subfolders = [
        str(Path(dir_path) / folder)
        for folder in os.listdir(dir_path)
        if os.path.isdir(os.path.join(dir_path, folder))
    ]

    lines_lst = []
    for folder in subfolders:
        string_line = "python app.py -p " + str(voice_pattern) + " -o "
        string_line += dir_path
        string_line += " -f "
        string_line += folder
        string_line += " -i " + str(immedia_decide)
        lines_lst.append(string_line)
    return lines_lst


def executed_lines(command_line_lst):
    for line in command_line_lst:
        s_e.execute_command_line(line)


def find_json_files(dir_path):
    json_files = []
    for root, _, files in os.walk(dir_path):
        for file in files:
            if file.endswith(".json"):
                json_files.append(os.path.join(root, file))
    return json_files


def extract_attributes(json_files, attributes) -> list:
    result_lst = []

    for json_file in json_files:
        with open(json_file, "r", encoding="utf-8") as file:
            content = json.load(file)
            for attribute in attributes:
                if attribute in content:
                    result_lst.append(content[attribute])
    return result_lst


def alternate_write_to_file(list01, list02, file_name="TextFromScripts.txt"):
    # 检查两个列表长度是否相等
    if len(list01) != len(list02):
        print("两个列表的长度不一致, 无法交替写入文件")
        return

    # 清空或创建文件
    with open(file_name, "w") as file:
        pass

    # 交替写入文件
    with open(file_name, "a") as file:
        # REM 在bat文件用以注释; 而在sh文件中则是用 # 来注释
        for index in range(len(list01)):
            file.write("REM " + list01[index] + "\n")
            file.write(list02[index] + "\n\n")


def executive_assistant():
    # 0:无声, 1:有声
    voice_pattern = 1
    # 0:不立即执行,1:立即执行
    immedia_decide = 0
    # 视频存放之路径
    store_dir = "C:\\DIR\\Paths\\F00\\files"
    # 要被提取的属性键值对的名称
    attributes = ["video_new_name"]

    # 初始化清理json文件目录
    delete_directory(pv.recording_file_folder)

    # 生成批量命令行内容列表
    command_line_lst = get_command_lines(store_dir, voice_pattern, immedia_decide)

    # 执行批量命令->生成json内容文件
    executed_lines(command_line_lst)

    json_files = find_json_files(pv.recording_file_folder)
    json_annotation_lst = extract_attributes(json_files, attributes)

    alternate_write_to_file(json_annotation_lst, command_line_lst)


executive_assistant()
